package com.zzyl.service.impl;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.zzyl.constant.Constants;
import com.zzyl.dto.UserLoginRequestDto;
import com.zzyl.entity.Member;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.MemberMapper;
import com.zzyl.service.CustomerUserService;
import com.zzyl.utils.JwtUtil;
import com.zzyl.utils.ObjectUtil;
import com.zzyl.vo.LoginVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

@Service
public class CustomerUserServiceImpl implements CustomerUserService {

    @Value("${zzyl.wechat.appId}")
    private String appId;

    @Value("${zzyl.wechat.appSecret}")
    private String appSecret;

    @Autowired
    private MemberMapper memberMapper;

    @Value("${zzyl.framework.jwt.base64-encoded-secret-key}")
    private String secretKey;

    @Value("${zzyl.framework.jwt.ttl}")
    private Integer ttl;

    /**
     * 微信登录
     *
     * @param dto
     * @return
     */
    @Override
    public LoginVo login(UserLoginRequestDto dto) {
        //1.根据code发送请求到微信 获取微信的唯一openid
        String openId = getOpenId(dto.getCode());


        //2.根据phonecode发送请求到微信 获取用户的手机号码
        String phone = getPhoneNumber(dto.getPhoneCode(), openId);
        //3.根据openid查询meber表,如果查询到了数据 则更新手机号码 如果没有查询到则新增一个用户
        Member member = memberMapper.queryByopenId(openId);
        if (member == null) {
            //当前登录人不是会员,需要注册
            member = new Member();

            String name = Constants.DEFAULT_NICKNAME_PREFIX.get((int) (Math.random() * Constants.DEFAULT_NICKNAME_PREFIX.size()));
            String PhoneNum = phone.substring(7);

            member.setName(name + PhoneNum);
            member.setOpenId(openId);
            member.setPhone(phone);
            member.setCreateTime(LocalDateTime.now());
            member.setUpdateTime(LocalDateTime.now());

            memberMapper.save(member);
        } else {
            //已经是会员的人 只修改手机号
            member.setPhone(phone);
            member.setUpdateTime(LocalDateTime.now());
            memberMapper.updata(member);
        }

        //4.生成token

        Map<String, Object> claims = new HashMap<>();
        claims.put("id", member.getId());
        claims.put("name", member.getName());
        String token = JwtUtil.createJWT(secretKey, ttl, claims);

        //5.构建返回值并返回
        LoginVo loginVo = new LoginVo();
        loginVo.setNickName(member.getName());
        loginVo.setToken(token);
        return loginVo;
    }


    private String getPhoneNumber(String PhoneCode, String openId) {
        //1.先获取访问的access_token
        String accessToken = getToken();

        //2.根据access_token和PhoneCode以及openId获取用户手机号
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("code", PhoneCode);
        paramMap.put("openid", openId);

        HttpResponse response = HttpUtil.createPost(Constants.WX_PHONE_URL + accessToken).body(JSONUtil.toJsonStr(paramMap)).execute();
        String json = response.body();
        if (ObjectUtil.isNotEmpty(json)) {
            JSONObject jsonObject = JSONUtil.parseObj(json);
            if (jsonObject.getInt("errcode").equals(0)) {
                JSONObject phoneInfo = jsonObject.getJSONObject("phone_info");
                String phoneNumber = phoneInfo.getStr("phoneNumber");
                return phoneNumber;
            } else {
                throw new BaseException(BasicEnum.GET_PHONE_ERROR);
            }
        } else {
            throw new BaseException(BasicEnum.GET_PHONE_ERROR);
        }
    }


    private String getToken() {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", appId);
        paramMap.put("secret", appSecret);
        paramMap.put("grant_type", "client_credential");
        HttpResponse response = HttpUtil.createGet(Constants.WX_TOKEN_URL).form(paramMap).execute();
        String json = response.body();
        if (ObjectUtil.isNotEmpty(json)) {
            JSONObject jsonObject = JSONUtil.parseObj(json);
            if (ObjectUtil.isNotEmpty(jsonObject.getStr("access_token"))){
                return jsonObject.getStr("access_token");
            }else {
                throw new BaseException(BasicEnum.GET_TOKEN_ERROR);
            }
        }else {
            throw new BaseException(BasicEnum.GET_TOKEN_ERROR);
        }
    }


    private String getOpenId(String code) {
        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("appid", appId);
        paramMap.put("secret", appSecret);
        paramMap.put("js_code", code);
        paramMap.put("grant_type", "authorization_code");
        //获取openid的时候失败了 会返回一个错误码
        HttpResponse response = HttpUtil.createGet(Constants.WX_LOGIN_URL).form(paramMap).execute();
        String json = response.body();
        if (ObjectUtil.isNotEmpty(json)){
            JSONObject jsonObject = JSONUtil.parseObj(json);
            if (ObjectUtil.isNotEmpty(jsonObject.getStr("openid"))){
                return jsonObject.getStr("appid");
            }else {
                throw new BaseException(BasicEnum.GET_OPENID_ERROR);
            }
        }else {
            throw new BaseException(BasicEnum.GET_OPENID_ERROR);
        }

    }


}
